import { Request, Response, NextFunction } from "express";
import Material from "../models/Material";
import { getToken } from "../utils/qiNiuUpload";
import fs from "fs";
import { v4 as uuidv4 } from "uuid";
// import { File } from "multer";
const _qiNiu_uri = 'http://assert.auage.cc/';
export const prefix = "/upload";
export const engine = "pug";

export const get = {
    async list(req: Request, res: Response, next: NextFunction) {
        const { flag, page = 1, pageSize = 20, meta = "image" } = req.params;
        const filter: any = {
            meta,
            sort: { createTime: -1 },
            page: page,
            limit: pageSize,
        };
        if (flag) {
            filter["flag"] = {
                $elemMatch: { $regex: new RegExp(`[\S]*${flag}[\S]*`) }
            };
        }
        console.log("filter==>", filter);
        const query = Material.find();
        const docs = await query.exec();
        res.send(JSON.stringify({
            code: 200,
            data: docs,
        }));
    },
    getToken(req: Request, res: Response) {
        res.send(JSON.stringify({
            code: 200,
            data: getToken(),
        }));
    }
}

export const post = {
    async add(req: Request, res: Response, next: NextFunction) {
        const { userid, meta = "image", flag, files = [], isSystem = false } = req.body;
        // const files = req.files as File[];
        
        // const readableStreams = files.map((file: any) => ({
        //     file: fs.createReadStream(file.path),
        //     ext: file.filename.substr(file.originalname.lastIndexOf('.') + 1),
        //     filename: file.originalname,
        // }));
        // const uploadInfo = await uploadFiles(readableStreams);
        const models = files.map((vo: any) => ({
            uid: uuidv4(),
            flag: !!flag ? flag.split(",") : [],
            meta,
            userid,
            name: vo.filename,
            metaSize: vo.fsize,
            isSystem: isSystem,
            uri: vo.path,
            createTime: new Date(),
        }));
        console.log("modelsss=>", models, req.body);
        const result = await Material.insertMany(models);
        res.send({
            code: 200,
            data: result,
        });
    }
}